package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.dao.UserDAO;
import it.unibz.ti2.internetPizzeria.entities.Employee;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.UserInfo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Changing orders' statuses from StatusReadyToDeliver to StatusInDelivery and
 * settings current user as order's deliverer.
 */
public class UpdateOrdersInDelivery extends HttpServlet {

	private static final long serialVersionUID = 3483560242540583932L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		OrderDAO orderDAO = null;
		try {
			orderDAO = new OrderDAO();
			orderDAO.openSession();
			UserDAO userDAO = new UserDAO();
			userDAO.openSession(orderDAO);

			String[] orderIds = request.getParameterValues("orderId");
			for (int i = 0; i < orderIds.length; i++) {
				Order order = orderDAO.getOrder(Long.parseLong(orderIds[i]));
				order.setStatus(Order.StatusInDelivery);
				UserInfo userInfo = (UserInfo) request.getSession()
						.getAttribute("userInfo");
				order.getDelivery().setDeliverer(
						(Employee) userDAO.getUser(userInfo.getId()));
				orderDAO.update(order);
			}
			ServletUtil.redirect(request, response, "/deliveryMap");
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (orderDAO != null) {
				orderDAO.closeSession();
			}
		}

	}
}
